<template>
	<view class="container-white">
		<view class="menu flex-box">
			<view>
				<image class="menu-icon" src="../../static/icon/icon-time.png" />
				<view>{{ remainingTime }}</view>
			</view>
			<view @click="goScantron">
				<image class="menu-icon" src="../../static/icon/icon-datika.png" />
				<view>答题卡</view>
			</view>
			<view @click="hidden = true">
				<image class="menu-icon" src="../../static/icon/icon-jiaojuan.png" />
				<view>交卷</view>
			</view>
			<view @click="collect">
				<image class="menu-icon" :src="questionList[testIndex].collect ? '../../static/icon/icon-collect-active.png' : '../../static/icon/icon-collect.png'" />
				<view>收藏</view>
			</view>
		</view>
		<view class="head flex-box" style="padding:10upx 20upx">
			<view>
				<text v-if="questionList[testIndex].quesType && parseInt(questionList[testIndex].quesType) === 1">单选题</text>
				<text v-if="questionList[testIndex].quesType && parseInt(questionList[testIndex].quesType) === 2">多选题</text>
				<text v-if="questionList[testIndex].quesType && parseInt(questionList[testIndex].quesType) === 3">判断题</text>
				<text>（{{ testIndex + 1 }}/{{ questionList.length }}）</text>
			</view>
		</view>

		<view class="topic-box">
			<!-- <rich-text v-if='topic.quesInfo' :nodes="topic.quesInfo" class="questions"></rich-text>
      <view v-if="topic.info">{{topic.info}}</view>-->
			<rich-text v-if="questionList[testIndex].info" :nodes="questionList[testIndex].info" class="questions"></rich-text>
			<view class="answer" v-if="questionList[testIndex].questionOptionEntities">
				<view class="options" v-for="(item, index) in questionList[testIndex].questionOptionEntities" @click="checkOptions(index)" :key="index">
					<view v-if="questionList[testIndex].quesType && parseInt(questionList[testIndex].quesType) !== 3" class="stide" :class="item.checked == true ? 'isCheck' : ''">
						{{ item.key }}
					</view>
					<view v-else class="stide" :class="item.checked === true ? 'isCheck' : ''"></view>
					<view style="flex:1">{{ item.option }}</view>
				</view>
			</view>
			<!-- <view hidden='true'>{{count}}</view> -->
		</view>

		<view class="footer">
			<button v-if="parseInt(testIndex) > 0" type="primary" class="primary footer-btn" @click="goPrevious">上一题</button>
			<view v-if="parseInt(testIndex) > 0" class="cut-off"></view>
			<button v-if="parseInt(testIndex) < parseInt(questionList.length) - 1" type="primary" class="primary footer-btn" @click="goNext">下一题</button>
			<button v-else type="primary" class="primary footer-btn" @click="hidden = true">交卷并查看结果</button>
		</view>

		<model v-if="hidden">
			<view class="model-content">交卷后将结束本次考试，确定交卷吗？</view>
			<view class="model-footer">
				<button class="model-footer-btn cancel" @click="hidden = false">取消</button>
				<button type="primary" class="model-footer-btn primary" @click="finishTopic">交卷</button>
			</view>
		</model>
	</view>
</template>

<script>
import { post_md5, post } from '../../common/request';
import { formatSeconds } from '../../common/common';
import { mapState } from 'vuex';
export default {
	data() {
		return {
			idx: 0,
			topic: {},
			totalCount: 0,
			hidden: false,
			// count: 0,
			examId: null,
			examType: '',
			remainingTime: '--:--',
			timer: 'onload',
			goPage: false
		};
	},
	onLoad(options) {
		this.examId = options.id;
		this.examType = Number(options.examType);
		this.initExam(options.id, options.duration)
	},
	onShow() {
		this.goPage = false;
		if (this.timer === null || this.timer === undefined) {
			this.Interval();
			this.timer = setInterval(_ => {
				this.Interval();
			}, 1000);
		}
		// if (parseInt(this.examType) === 1) this.getExam();
	},
	onBackPress() {
		this.hidden = true;
		return true;
	},
	onUnload() {
		if (this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	},
	computed: mapState(['questionList', 'testIndex']),
	methods: {
		Interval() {
			let second = uni.getStorageSync('second');
			if (second > 0) {
				second--;
				this.remainingTime = formatSeconds(second);
				uni.setStorageSync('second', second);
			} else {
				clearInterval(this.timer);
				this.timer = null;
				this.finishTopic();
			}
		},
		initExam(examId, examDuration) {
			let quesList = uni.getStorageSync('quesList');
			quesList.forEach(x => {
				if (!x.userAnsw) x.userAnsw = '';
			});
			
			
			uni.setStorageSync('second', examDuration || 0);
			
			this.Interval();
			this.timer = setInterval(_ => {
				this.Interval();
			}, 1000);
			this.$store.commit('setTestIndex', uni.getStorageSync('examIndex'));
			this.selectCollect();
		},

		// 选择选项
		checkOptions(index) {
			let { questionOptionEntities, quesType } = this.questionList[this.testIndex];
			if (parseInt(quesType) === 2) {
				this.$store.commit('setQuestionListChecked', {
					testIndex: this.testIndex,
					index,
					Bool: !questionOptionEntities[index].checked
				});
			} else {
				questionOptionEntities.forEach((_, index) => {
					this.$store.commit('setQuestionListChecked', {
						testIndex: this.testIndex,
						index,
						Bool: false
					});
				});
				this.$store.commit('setQuestionListChecked', {
					testIndex: this.testIndex,
					index,
					Bool: true
				});
			}
			this.$store.commit('setQuestionListUserAnsw', {
				testIndex: this.testIndex,
				answ: this.questionList[this.testIndex].questionOptionEntities
					.filter(x => x.checked)
					.map(x => x.key)
					.sort()
					.join('')
			});
			this.$forceUpdate();
			// if (parseInt(this.examType) === 1) this.saveTopic();
			this.saveTopic()
		},

		// 下一题
		goNext() {
			if (this.testIndex + 1 < this.questionList.length) {
				this.$store.commit('setTestIndex', this.testIndex + 1);
				this.selectCollect();
			}
			uni.setStorageSync('examIndex', this.testIndex);
		},
		// 上一题
		goPrevious() {
			if (this.testIndex > 0) {
				this.$store.commit('setTestIndex', this.testIndex - 1);
				this.selectCollect();
			}
			uni.setStorageSync('examIndex', this.testIndex);
		},

		saveTopic() {
			post_md5('/exam-app/exam/savequesrecord', {
				examId: this.examId,
				quesId: this.questionList[this.testIndex].quesId,
				userId: uni.getStorageSync('userId'),
				selfAnsw: this.questionList[this.testIndex].questionOptionEntities
					.filter(x => x.checked)
					.map(x => x.key)
					.sort()
					.join('')
			});
		},

		finishTopic() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			post_md5(
				'/exam-app/exam/submitpaper',
				{
					// examQuesList: JSON.stringify(
					// 	this.questionList.map(x => ({
					// 		quesId: x.quesId,
					// 		userAnsw: x.userAnsw
					// 	}))
					// ),
					examId: this.examId,
					userId: uni.getStorageSync('userId')
				},
				false
			).then(res => {
				if (res.code == 500) {
					uni.reLaunch({
						url: 'examination-error?error=' + res.msg
					});
				} else {
					uni.reLaunch({
						url: 'examination-result?id=' + this.examId
					});
				}
			});
		},
		// 查看答题卡
		goScantron() {
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = null;
			}
			if (parseInt(this.examType) === 1) {
				this.saveTopic();
				uni.navigateTo({
					url: `scantron?examId=${this.examId}`
				});
			} else {
				uni.navigateTo({
					url: `scantron?examId=${this.examId}`
				});
			}
		},

		// 查询收藏信息
		selectCollect() {
			const params = {
				examType: this.examType,
				type: 3,
				userId: uni.getStorageSync('userId'),
				idInfo: this.questionList[this.testIndex].quesId
			};
			post_md5('/usercenter-app/collect/iscollect', params, false).then(res => {
				if (res.data == -1) {
					this.$store.commit('setQuestionListIscollect', {
						testIndex: this.testIndex,
						isShowToast: false,
						val: null
					});
				} else {
					this.$store.commit('setQuestionListIscollect', {
						testIndex: this.testIndex,
						isShowToast: false,
						val: res.data
					});
				}
			});
		},

		// 收藏
		collect() {
			if (this.questionList[this.testIndex].collect) {
				const params = {
					id: this.questionList[this.testIndex].collect
				};
				post_md5('/usercenter-app/collect/cancelcollect', params, false).then(res => {
					this.$store.commit('setQuestionListIscollect', {
						testIndex: this.testIndex,
						isShowToast: true,
						val: false
					});
				});
			} else {
				const params = {
					examType: this.examType,
					type: 3,
					userId: uni.getStorageSync('userId'),
					idInfo: this.questionList[this.testIndex].quesId
				};
				post_md5('/usercenter-app/collect/collectInfo', params, false).then(res => {
					this.$store.commit('setQuestionListIscollect', {
						testIndex: this.testIndex,
						isShowToast: true,
						val: res.data
					});
					// this.count++
					uni.showToast(
						{
							title: '收藏成功',
							icon: 'none'
						},
						500
					);
				});
			}
		},
		getUserAnsw() {
			uni.showLoading();
			const params = {
				examId: this.examId,
				userId: uni.getStorageSync('userId'),
				quesId: this.topic.id
			};
			post_md5('/exam/getAnswByExamUser', params).then(res => {
				uni.hideLoading();
				if (res.data) {
					for (let i in res.data) {
						for (let j in this.topic.optionsBeans) {
							if (res.data[i] == this.topic.optionsBeans[j].key) {
								this.topic.optionsBeans[j].checked = true;
								break;
							} else {
								this.topic.optionsBeans[j].checked = false;
							}
						}
					}
				}
			});
		}
	}
};
</script>

<style>
.menu {
	display: flex;
	font-size: 22upx;
	font-weight: 400;
	color: #333333;
	padding: 10upx 100upx;
	margin: 1px 0;
	border-bottom: 1px solid #ededed;
	text-align: center;
}

.menu-icon {
	width: 42upx;
	height: 42upx;
}

.topic-box {
	padding: 20upx;
	font-size: 28upx;
	font-weight: normal;
	color: #333333;
	line-height: 60upx;
}

.footer {
	height: 98upx;
	font-size: 28upx;
	background: #02a8f4;
}
</style>
<style scoped>
.isCheck {
	background: #02a8f4;
	color: #ffffff;
}
</style>
